<template>
  <div :style="backgroundDiv">
    <div class="main">
      <!-- <lang-select class="right-menu-item hover-effect" /> -->
      <div class="box">
        <div class="content">
          <div class="people" style="display: none;">
            <img :src="imgSrc" width="100%" height="100%" alt="">
          </div>
          <div class="permission-container">
            <div class="permission-form">
              <div class="logo">
                <img :src="logoSrc" height="100%" alt="">
              </div>
              <div class="text">{{ $t('login.text') }}</div>
              <template v-if="loginType === 'form'">
                <form-login ref="refFormLogin" @clickLogin="clickFormLogin">
                  <template v-slot:EXTENDFORM>
                    <!-- 滑动验证 -->
                    <!-- <div class="login_move_out" style="padding-bottom: 22px;">
                      <el-popover v-model="moveVerificationVisible" placement="top" width="350" trigger="manual" @show="$refs.moveVerification.refresh()">
                        <move-verification ref="moveVerification" @success="disableLogin = false" @close="moveVerificationVisible = false" />
                        <el-button slot="reference" :type="disableLogin ? 'primary' : 'success'" class="gl_button_long" @click="moveVerificationVisible = true">{{ disableLogin ? '滑动验证' : '验证通过' }}</el-button>
                      </el-popover>
                    </div> -->
                    <!-- <el-form-item>
                      <span class="svg-container">
                        <i class="el-icon-picture" />
                      </span>
                      <el-input v-model="verificationCode" :placeholder="$t('login.verificationCode')" name="verificationCode" type="text" tabindex="3" style="width: 60%;" auto-complete="on" @keyup.enter.native="clickFormLogin" />
                      <div style="height: 40px;width: 31%;vertical-align: middle;text-align:center;display: inline-block;">
                        <img style="height: 40px;" src="../../assets/images/logo/logo.png" alt="">
                      </div>
                    </el-form-item> -->
                  </template>
                  <template v-slot:FORMLOGIN>
                    <!-- <el-row style="margin-bottom:20px;">
                      <el-col :span="12">
                        <el-checkbox v-model="userRemember">{{ $t('login.rememberMe') }}</el-checkbox>
                      </el-col>
                      <el-col :span="12">
                        <div align="right">
                          <el-button size="mini" type="text" @click="changeLoginType(loginType)">
                            <template v-if="loginType === 'msg'">
                              {{ language==='zh'?'用户名密码登录':'EN用户名密码登录' }}
                            </template>
                            <template v-else-if="loginType === 'form'">
                              {{ language==='zh'?'短信验证登录':'EN短信验证登录' }}
                            </template>
                          </el-button>
                        </div>
                      </el-col>
                    </el-row> -->
                    <el-row class="forget">
                      <div class="au_login" style="visibility: hidden;">
                        <el-checkbox v-model="automatic">{{ $t('login.automatic') }}</el-checkbox>
                      </div>
                      <div class="forgetpassword">
                        <el-button type="text" @click="routerRedirect('forgetPassword')">{{ $t('login.forgetPwd') }}</el-button>
                      </div>
                    </el-row>
                    <div class="login_move_out" style="padding-bottom: 4px;">
                      <el-button slot="reference" :loading="loading" type="primary" class="gl_button_long" @click.native.prevent="clickLogin">{{ $t('login.logIn') }}</el-button>
                    </div>
                  </template>
                </form-login>
              </template>
              <template v-if="loginType === 'msg'">
                <msg-login ref="refMsgLogin">
                  <template v-slot:MSGLOGIN>
                    <!-- <el-row style="margin-bottom:20px;">
                      <el-col :span="12">
                        <el-checkbox v-model="userRemember">{{ $t('login.rememberMe') }}</el-checkbox>
                      </el-col>
                      <el-col :span="12">
                        <div align="right">
                          <el-button size="mini" type="text" @click="changeLoginType(loginType)">
                            <template v-if="loginType === 'msg'">
                              {{ language==='zh'?'用户名密码登录':'EN用户名密码登录' }}
                            </template>
                            <template v-else-if="loginType === 'form'">
                              {{ language==='zh'?'短信验证登录':'EN短信验证登录' }}
                            </template>
                          </el-button>
                        </div>
                      </el-col>
                    </el-row> -->
                    <el-button :loading="loading" type="primary" class="gl_button_long" @click.native.prevent="clickMsgLogin">{{ $t('login.logIn') }}</el-button>
                  </template>
                </msg-login>
              </template>
              <template v-if="loginType === 'valid'">
                <template v-if="showVerifyCodeModel">
                  <el-row>
                    <el-col :span="24">
                      <div class="title-container">
                        <h3 class="title">{{ $t('login.verification') }}</h3>
                      </div>
                    </el-col>
                  </el-row>
                  <verify-code @showVerifyCodeModel="getVerificationData" />
                </template>
              </template>
              <form id="SubmitForm" class="login_form" name="login_form" method="post" :action="actions">
                <input id="action" type="text" value="Login" name="action">
                <input id="password" type="password" value="" name="password">
                <input id="verificationCode" type="verificationCode" value="" name="verificationCode">
                <input id="userNameOrEmailAddress" type="text" value="" name="userNameOrEmailAddress">
                <input id="ReturnUrl" type="text" value="" name="ReturnUrl">
                <input id="tenantId" type="text" value="" name="tenantId">
                <input id="verCodeId" type="text" value="" name="verCodeId">
                <input id="verCodeValue" type="text" value="" name="verCodeValue">
              </form>
              <!-- <el-divider>{{ $t('login.otherLoginType') }}</el-divider> -->
              <other-login v-if="env !== 'version'" :tenantid="tenantId" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="archival_copyright">
      <div class="archival">版权所有 © {{ copyright }} <a :href="archivalUrl">苏ICP备{{ archival }}号</a></div>
      <div class="copyright">
        <a :href="archivalUrl">
          <img :src="archivalImg" alt="">
          苏公网安备 {{ archival }}号
        </a>
      </div>
    </div>
    <!-- 拖动弹出 -->
    <el-dialog class="gl_move_dialog" :visible.sync="moveVerificationVisible" :show-close="false" :close-on-click-modal="false" width="350px" @opened="$refs.moveVerification.refresh()">
      <move-verification ref="moveVerification" :envir="'pc'" @success="clickFormLogin" @close="moveVerificationVisible = false" />
    </el-dialog>
  </div>
</template>
<script>
// import LangSelect from '@/components/LangSelect';
import verifyCode from '@/components/VerifyCode/index';
import { mapState, mapActions } from 'vuex';
import archivalImg from '@/assets/images/beian.png';
import {
  getLoginError,
  deleteLoginError,
  getLoginErrorUserMsg,
  deleteLoginErrorUserMsg
} from '@/lib/auth';
// import { getQueryData } from '@/lib/index';
import moveVerification from '@/plugin/Verification/move.vue';
import otherLogin from './otherLogin';
export default {
  components: {
    // LangSelect,
    verifyCode,
    moveVerification,
    otherLogin
  },
  props: {
    tenantId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      env: process.env.VUE_APP_DIREVTOR,
      actions: '',
      backgroundDiv: {
        backgroundImage: 'url(' + require('@/assets/images/bg.png') + ')',
        backgroundRepeat: 'no-repeat',
        backgroundSize: '100% 100%'
      },
      imgSrc: '',
      logoSrc: require('@/assets/images/logo/logo_word.png'),
      archivalImg: archivalImg,
      loading: false,
      loginType: 'form',
      userRemember: false,
      automatic: false,
      redirect: undefined,
      otherQuery: {},
      showVerifyCodeModel: false, // 控制是否显示验证码,true为显示验证模块
      verificationCode: '', // 验证码
      moveVerificationVisible: false, // 验证弹框
      disableLogin: true, // 登陆按钮不可用
      showTenantId: true // 是否显示tenantId
    };
  },
  computed: {
    ...mapState({
      archival: state => state.app.archival,
      archivalUrl: state => state.app.archivalUrl,
      copyright: state => state.app.copyright,
      copyrightUrl: state => state.app.copyrightUrl
    })
    // ...mapState({
    //   language: state => state.app.language
    // })
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = route.query && route.query.redirect;
          this.otherQuery = this.getOtherQuery(this.redirect);
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.actions =
      WEB_CONFIG.VUE_APP_LOGIN_BASE +
      '/api/account/login?ReturnUrl=' +
      this.getReturnUrl();
    document.getElementById('SubmitForm').action = this.actions;
    const errorCode = getLoginError();
    if (errorCode) {
      this.$message.error(errorCode.msg);
      deleteLoginError();
      if (
        [
          'UserNotFound',
          'NotAllowed',
          'RequiresTwoFactor',
          'LockedOut',
          'Disabled',
          'InvalidPassword',
          'TenantDisabled',
          'TenantNotFound',
          'InvalidVerificationCode',
          'OrganizationUnitDisabled'
        ].includes(errorCode.code)
      ) {
        const userMsg = getLoginErrorUserMsg();
        this.$refs.refFormLogin['FormLoginVO'].userNameOrEmailAddress =
          userMsg.user;
        this.$refs.refFormLogin['FormLoginVO'].password = userMsg.password;
        console.log(userMsg);
        deleteLoginErrorUserMsg();
      }
    }
  },
  methods: {
    ...mapActions({ setMarkTelephone: 'app/setMarkTelephone' }),
    clickLogin() {
      this.$refs.refFormLogin.$refs['refFormLogin'].validate(valid => {
        if (valid) {
          this.moveVerificationVisible = true;
        }
      });
    },
    // 1. 切换登录方式 form：账号、密码登录 msg：账号、手机验证码登录; 2.并且记录已输入的手机号
    changeLoginType(type) {
      if (type === 'msg') {
        this.loginType = 'form';
        this.setMarkTelephone(
          this.$refs.refMsgLogin.MsgLoginVO.userNameOrEmailAddress
        );
      }
      if (type === 'form') {
        this.loginType = 'msg';
        this.setMarkTelephone(
          this.$refs.refFormLogin.FormLoginVO.userNameOrEmailAddress
        );
      }
    },
    // 获取returnUrl
    getReturnUrl() {
      let ReturnUrl = this.$route.query['ReturnUrl']
        ? this.$route.query['ReturnUrl']
        : '';
      if (
        ReturnUrl &&
        ReturnUrl.length > 2 &&
        ReturnUrl.substring(ReturnUrl.length - 2) === '#/'
      ) {
        ReturnUrl = ReturnUrl.substring(0, ReturnUrl.length - 2);
      }
      return ReturnUrl;
    },
    // 验证模块返回后调用方法
    getVerificationData(data) {
      console.log(data);
      this.showVerifyCodeModel = data.showVerifyCodeModel;
      // 当人机验证返回验证码正确时
      this.loginType = 'form';
      this.showVerifyCodeModel = false;
    },
    // form 账号、密码登录提交
    clickFormLogin(moveData) {
      this.$refs.refFormLogin.$refs['refFormLogin'].validate(valid => {
        if (valid) {
          console.log(this.actions);
          this.loading = true;
          const params = {
            ReturnUrl: this.getReturnUrl(),
            action: 'Login',
            tenantId: this.tenantId,
            verCodeId: moveData.ClientId,
            verCodeValue: moveData.Verification
          };
          for (const i in this.$refs.refFormLogin['FormLoginVO']) {
            // params['LoginInput.' + i] = this.$refs.refFormLogin['FormLoginVO'][i];
            params[i] = this.$refs.refFormLogin['FormLoginVO'][i];
          }
          for (const i in params) {
            console.log(document.getElementById(i).value);
            document.getElementById(i).value = params[i];
          }
          document.getElementById('SubmitForm').submit();
        } else {
          return false;
        }
      });
    },
    // msg 账号、手机验证码登录提交
    clickMsgLogin() {
      this.$refs.refMsgLogin.$refs['refMsgLogin'].validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch(
              'user/Account/Login',
              this.$refs.refMsgLogin['MsgLoginVO']
            )
            .then(() => {
              localStorage.setItem('userRemember', true);
              if (this.redirect) {
                window.location.href = this.redirect;
              } else {
                this.$router.push({
                  path: this.redirect || '/',
                  query: this.otherQuery
                });
              }
              this.loading = false;
            })
            .catch(error => {
              this.$refs.refMsgLogin.MsgLoginVO.verifyCode = '';
              this.loading = false;
              localStorage.setItem('userRemember', false);
              if (error.code === 60201 || error.code === 6020) {
                this.multiplePwdError('refMsgLogin', 'MsgLoginVO');
              }
            });
        } else {
          return false;
        }
      });
    },
    multiplePwdError(ref, type) {
      // 限制密码输入错误次数，超过*次跳转至人机验证
      const _this = this;
      const multiplePwdError = JSON.parse(
        localStorage.getItem('multiplePwdError')
      );
      if (!multiplePwdError) {
        const data = [
          {
            userNameOrEmailAddress:
              _this.$refs[ref][type].userNameOrEmailAddress,
            errorNum: 1
          }
        ];
        localStorage.setItem('multiplePwdError', JSON.stringify(data));
      } else {
        // 标记缓存里是否存在该用户名
        let mark = false;
        multiplePwdError.filter((item, index) => {
          if (
            item.userNameOrEmailAddress ===
            _this.$refs[ref][type].userNameOrEmailAddress
          ) {
            item.errorNum = Number(item.errorNum) + 1;
            mark = true;
            if (item.errorNum > 2) {
              _this.loginType = 'valid';
              _this.showVerifyCodeModel = true;
            } else {
              _this.showVerifyCodeModel = false;
            }
          }
        });
        if (!mark) {
          multiplePwdError.unshift({
            userNameOrEmailAddress:
              _this.$refs[ref][type].userNameOrEmailAddress,
            errorNum: 1
          });
        }
        localStorage.setItem(
          'multiplePwdError',
          JSON.stringify(multiplePwdError)
        );
      }
    },
    routerRedirect(path) {
      const number =
        this.loginType === 'msg'
          ? this.$refs.refMsgLogin.MsgLoginVO.userNameOrEmailAddress
          : this.$refs.refFormLogin.FormLoginVO.userNameOrEmailAddress;
      this.setMarkTelephone(number);
      this.$router.push({
        name: path,
        query: this.$route.query,
        params: this.$route.params
      });
    },
    getOtherQuery(query) {
      if (query) {
        return Object.keys(query).reduce((acc, cur) => {
          if (cur !== 'redirect') {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.main {
  min-height: calc(100vh - 70px);
  display: flex;
  align-items: center;
  justify-content: center;
}
.archival_copyright {
  height: 70px;
  padding-top: 10px;
  line-height: 30px;
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.archival_copyright a {
  transition: all 0.3s ease;
}
.archival_copyright a:hover {
  text-decoration: underline;
}
.copyright img {
  vertical-align: middle;
  margin-right: 2px;
  width: 18px;
}
.login_form {
  display: none;
}
.box {
  width: 700px;
  min-width: 600px;
  min-height: 500px;
}
.content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .people {
    width: 45%;
    min-width: 200px;
  }
}
.forget {
  color: #073190;
  line-height: 22px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 22px;
  font-size: 14px;
  margin-bottom: 10px;
  .au_login {
    display: inline-block;
    width: 300px;
  }
  .forgetpassword {
    display: inline-block;
  }
}
</style>
